<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <style>
    .content {
      position: relative;
      border: 5px solid green;
      width: 100%;
      min-height: 600px;
    }

    .content div {
      position: absolute;
      border: 2px solid blue;
    }
  </style>
</head>

<body>
  <!-- 瀑布流，宽度一致，高度不一致 -->
  <div class="content" id="contentBox">

  </div>

  <script>
     var contentBox = document.querySelector("#contentBox");
     var total = 0;
      // 计算父容器的宽度,计算每行最多容纳多少个元素
      var parentBoxWidth = contentBox.clientWidth;
      var rowNumber = Math.floor(parentBoxWidth / 100);

      // 计算上一列元素的高度
      function calcLastIndexTop() {
        // total < rowNumber , 就说明是第一行
        if (total < rowNumber) return 0;
        var lastIndex = total - rowNumber;
        var lastRowIndexHeight = contentBox.children[lastIndex].clientHeight + 2 * 2;
        var lastRowIndexTop = parseInt(contentBox.children[lastIndex].style.top);
        return lastRowIndexTop + lastRowIndexHeight;
      }

      /*
         返回一个对象{left:"10px", top:"10px"}
      */
      function getCurrentLeftAndTop() {
        // 在行上的相对位置index 
        var presentRowIndex = total % rowNumber;
        var left = presentRowIndex * 100 + "px";
        var top = calcLastIndexTop() + "px";
        return { left, top }
      }


      function insertIntoContent(){
          let { left, top } = getCurrentLeftAndTop();   
          let presentBox = createBox();
          presentBox.style.left = left;
          presentBox.style.top = top;
          contentBox.append(presentBox);
          total++;
      }
       // 定时器模拟异步当我们拿到dom 对象数组的时候，循环getCurrentLeftAndTop() 这个就好
       function getDoms(){
          var timer = setInterval(() => {
          if (total < 10) {
            insertIntoContent();
          } else {
            clearInterval(timer);
          }

        }, 1000);

       }
      
       getDoms();

      // 封装使用waterFall
      /* 
        container ,一个容器可以是一个dom 对象，也可以是一个css 选择器
        默认是3 ， 也就是经典的三列布局
      */
      function waterFall(container,rowMaxNumber = 3  ){
        var container = container.nodeType ? container:document.querySelector(container);
        var containerWidth = contentBox.clientWidth;
        var rowMaxNumber = rowMaxNumber; // 每行最多容纳多少item

      }



    



    // 创建一个宽高随机的box div 模拟页面的不同区域部分
    function createBox() {
      var box = document.createElement("div");
      box.style.width = "100px";
      box.style.height = RandomInt() + "px";
      return box;
    }

    function RandomInt() {
      var min = 100;
      var length = 200;
      return min + Math.floor(Math.random() * length);
    }
  </script>
</body>

</html>